package cn.lzy.demo;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * @Description
 * @Author lzy
 * @Date 2024/1/4 10:02
 * @Version
 **/
@Aspect
@Component
public class MyTxAspect {

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Pointcut("@annotation(MyTx) || @within(MyTx)")
    public void pc() {

    }

    @Around("pc()")
    public Object around(ProceedingJoinPoint pjp) {
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        Object result = null;
        try {
             result = pjp.proceed();
             transactionManager.commit(status);
        } catch (Throwable e) {
            transactionManager.rollback(status);
        }

        return result;
    }
}
